package com.taptech.doufu.ktexpand

import android.graphics.Color
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.widget.TextView
import java.lang.Exception

fun TextView.setTextWithAt(content:String){
    if (content.isNullOrEmpty()) {
        return
    }
    if (content.contains("@")){
        try {
            val split = content.replace("\r\n".toRegex()," ")
                    .replace("\n".toRegex()," ")
                    .split(" ")
                    .filter { it.contains("@") }
                    .map {
                        val index = it.indexOf("@")
                        if (index == -1) it else it.substring(index, it.length)
                    }

            val spannableString = SpannableStringBuilder()
            spannableString.append(content)
            for (i in split.indices) {
                val word = split[i]
                var index = spannableString.toString().indexOf(word)
                if (index > -1) {
                    val littleSpan = ForegroundColorSpan(Color.parseColor("#5793d9"))
                    spannableString.setSpan(littleSpan, index, index + word.length, Spannable.SPAN_PRIORITY)
                }
            }
            this.text = spannableString
            return
        } catch (e: Exception) {
            e.printStackTrace()
            this.text = content
        }

    }
    this.text = content
}